#include "samples.h"

SHELL_CMD_FN(_os_sample_fifo);

SHELL_REGISTER_CMD(
    register_sample_fifo,
    SHELL_SETUP_CMD("sample-fifo", "OS API example of: fifo", _os_sample_fifo, NULL), //
);

struct sample_struct
{
    uint8_t index;
    uint32_t data;
};

static os_fifo_t s_fifo_handle;

SHELL_CMD_FN(_os_sample_fifo)
{
    tag();

    struct sample_struct *fifo_data;

    do
    {
        printf("create a fifo object\r\n");
        if (os_fifo_q_create(&s_fifo_handle) != OS_OK)
        {
            break;
        }

        printf("allocation fifo memory\r\n");
        fifo_data = os_fifo_alloc(sizeof(struct sample_struct));
        if (fifo_data == NULL)
        {
            break;
        }
        fifo_data->index = 1;
        fifo_data->data = 0x12345678;

        printf("put the memory into the fifo object\r\n");
        if (os_fifo_put(&s_fifo_handle, fifo_data) != OS_OK)
        {
            break;
        }

        printf("allocation and put the memory into the fifo object agaen\r\n");
        fifo_data = os_fifo_alloc(sizeof(struct sample_struct));
        if (fifo_data == NULL)
        {
            break;
        }
        fifo_data->index = 2;
        fifo_data->data = 0x9abcdef0;
        if (os_fifo_put(&s_fifo_handle, fifo_data) != OS_OK)
        {
            break;
        }

        printf("try to take the memory from fifo object\r\n");
        fifo_data = os_fifo_take(&s_fifo_handle, 0);
        if (fifo_data == NULL || fifo_data->index != 1)
        {
            break;
        }
        printf("the test data value = 0x%x\r\n", fifo_data->data);

        printf("must release the memory or put again\r\n");
        os_fifo_free(fifo_data);

        printf("try to take the memory from fifo object again\r\n");
        fifo_data = os_fifo_take(&s_fifo_handle, 0);
        if (fifo_data == NULL || fifo_data->index != 2)
        {
            break;
        }
        printf("the test data value = 0x%x\r\n", fifo_data->data);
        os_fifo_free(fifo_data);

        printf("return NULL when the fifo object is empty\r\n");
        fifo_data = os_fifo_take(&s_fifo_handle, 0);
        if (fifo_data != NULL)
        {
            break;
        }

        printf("objects can be deleted when they are no longer used\r\n");
        os_fifo_q_delete(&s_fifo_handle);

        printf("operate success\r\n");
        return 0;

    } while (0);

    os_fifo_q_delete(&s_fifo_handle);

    printf("operate fail!\r\n");
    return -1;
}
